package main

import (
    "net/http"
    "encoding/json"
    "fmt"
    "strings"
    "io/ioutil"
    "crypto/tls"
)

var g_auth_data []byte
var g_final_ticket string
var g_final_token string

type RootAuth struct {
    Data RootAuthPro `json:"data"`
}

//结构体中不需要的字段可以不用写
type RootAuthPro struct {
    //Clustername string `json:"clustername"`
    //Username string `json:"username"`
    Ticket string `json:"ticket"`
    Token string `json:"CSRFPreventionToken"`
}

func get_ticket(url string, post_data string) int {

    reader := strings.NewReader(post_data)
    request, err := http.NewRequest("POST", url, reader)
    if err != nil {
        fmt.Println(err.Error())
        return -1
    }
    /* 加head */
    //request.Header.Set("Content-Type", "application/json;charset=UTF-8")

    //curl -k
    tr := &http.Transport{
        TLSClientConfig:&tls.Config{InsecureSkipVerify: true},
    }
    client := &http.Client{Transport: tr}

    resp, err := client.Do(request)
    if err != nil {
        fmt.Println(err.Error())
        return -1
    }
    
    defer resp.Body.Close()

    resp_bytes, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Println(err.Error())
        return -1
    }

    g_auth_data = resp_bytes

    //fmt.Println(resp_bytes) //此处显示[]byte类型都是十六进制数
    fmt.Printf("\n%s\n\n", g_auth_data) //显示字符串
    return 0;
}

func parse_ticket() int {

    var data_auth RootAuth
    err1 := json.Unmarshal(g_auth_data, &data_auth) 
    if err1 != nil {
        fmt.Println(err1.Error())
        return -1
    }
    
    /* 如果是go的方式set,add, 不需要加cookie:和CSRFPreventionToken: */
    g_final_ticket = "PVEAuthCookie=" + data_auth.Data.Ticket
    g_final_token = data_auth.Data.Token

    fmt.Printf("g_final_ticket=%s\ng_final_token=%s\n\n", g_final_ticket, g_final_token)

    return 0
}